package leetCode.thread.leetCode1226;

import java.util.concurrent.Semaphore;

public class Solution1 implements DiningPhilosophers{


    // 定义叉子信号量资源
    Semaphore[] fork = new Semaphore[5];

    public Solution1(){
        for(int i=0;i<5;i++){
            fork[i] = new Semaphore(1);
        }
    }

    @Override
    public void wantsToEat(int philosopher,
                           Runnable pickLeftFork,
                           Runnable pickRightFork,
                           Runnable eat,
                           Runnable putLeftFork,
                           Runnable putRightFork) throws InterruptedException {

        int fork2 = (philosopher+1)%5;
        fork[Math.min(philosopher,fork2)].acquire();
        fork[Math.max(philosopher,fork2)].acquire();
        pickLeftFork.run();
        pickRightFork.run();
        eat.run();
        putLeftFork.run();
        putRightFork.run();
        fork[Math.min(philosopher,fork2)].release();
        fork[Math.max(philosopher,fork2)].release();
    }

}
